package cn.fl.finance.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.fl.finance.condition.FinLoanDtlQC;
import cn.fl.finance.constant.FinLoanConstant;
import cn.fl.finance.service.IFinLoanApplyService;
import cn.fl.finance.service.IFinLoanDtlService;
import cn.fl.finance.service.IFinLoanInfoService;
import cn.fl.finance.service.IFinPayApplyInfoService;
import cn.fl.finance.vo.FinLoanDtlVO;
import cn.fl.finance.vo.FinLoanInfoVO;
import cn.fl.finance.vo.FinPayApplyInfoVO;
import cn.fl.finance.vo.FinPayDtlGridVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.vo.SysUsrVO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 借款申请
 * 作者:hongyanbo
 * 时间:2018/9/27
 */
@Controller
@RequestMapping("/capital/finance/loan/apply")
public class FinLoanApplyController {
    @Autowired
    private IFinLoanApplyService finLoanApplyService;
    @Autowired
    private IFinLoanInfoService finLoanInfoService ;
    @Autowired
    private IFinLoanDtlService finLoanDtlService;
    @Autowired
    private ISysDictionaryApiService dictionaryApiService;
    @Autowired
    private IFinPayApplyInfoService payApplyInfoService;
    @Autowired
    private ISysOrgApiService orgApiService;
    @Autowired
    ISysUsrService sysUsrService;

    /**
     * 借款申请主页面
     * @param model
     * @param isMust 流程附加页面控制字段:0表示可以编辑 1表示不可编辑
     * @param isAccount 流程附加页面控制字段 :0表示帐号可以编辑 1表示帐号不可以编辑
     * @param showSaveBtn 0:不显示保存按钮，1：显示
     * @param applyInfoId 有ID代表是修改已有申请，没ID代表是新建申请
     * @param showSaveApplyBtn 0隐藏 1显示   《暂存》和《保存并提交申请流程》按钮控制
     * @param payDtlEditable 0：不可编辑 1：可编辑 付款申请明细是否可编辑
     * @param bankAccEditable 0：不做任何操作 1：可编辑 付款申请明细是否可编辑
     * @return
     */
    @RequestMapping("toAddPage.do")
    public ModelAndView toAddPage(ModelAndView model,String loanInfoId ,
                                  @RequestParam(required = false,defaultValue = "0") String bankAccEditable,
                                  @RequestParam(required = false,defaultValue = "0") String isMust,
                                  @RequestParam(required = false,defaultValue = "0") String isAccount ,
                                  @RequestParam(required = false,defaultValue = "0") String newFlag ,
                                  @RequestParam(required = false,defaultValue = "0") String showSaveBtn,
                                  @RequestParam(required = false,defaultValue = "1") String showSaveApplyBtn,
                                  @RequestParam(required = false,defaultValue = "1") String payDtlEditable,
                                  String applyInfoId,String isNeedUpload){
        if(StringUtils.isBlank(loanInfoId) && StringUtils.isNotBlank(applyInfoId)){ //从list修改按钮进来 没loaninfoid 所以查一下
            FinPayApplyInfoVO applyInfoVO = payApplyInfoService.selectById(Long.valueOf(applyInfoId));
            loanInfoId = String.valueOf(applyInfoVO.getLoanId());
        }
        if(StringUtils.isNotBlank(loanInfoId)){ //修改
            FinLoanInfoVO finLoanInfoVO = this.finLoanInfoService.selectById(Long.valueOf(loanInfoId));
            model.addObject("loanDate", DateUtils.formatDateToString(finLoanInfoVO.getLoanTm(),DateUtils.YYYY_MM_DD));
            Long totalAmt = this.finLoanInfoService.getTotalAmt(Long.valueOf(loanInfoId));
            model.addObject("totalAmt", DecimalUtils.convertFenToYuan(totalAmt));
            SysUsrVO sysUsrVO = sysUsrService.selectById(finLoanInfoVO.getCstMgrId(), CurrentThreadContext.getCurrentSysCd());
            if(sysUsrVO!=null){
                model.addObject("usrMobile",sysUsrVO.getMp());
            }
            model.addObject("usrNm", finLoanInfoVO.getCstMgrNm());
            String cstMgrOrgCd = finLoanInfoVO.getCstMgrOrgCd();
            SysOrgDTO sysOrgDTO = orgApiService.selectSysOrgByOrgCd(cstMgrOrgCd, "11000");
            model.addObject("usrOrgCd",sysOrgDTO.getOrgDispNm());
            // 查看有没有is_del=2 的申请数据，如果有 则显示出来
            Long tempId = this.finLoanApplyService.selectTempApplyIdByLoanInfoId(loanInfoId);
            if(StringUtils.isBlank(applyInfoId)){
                model.addObject("newFlag","0");
                if(tempId!=null){
                    applyInfoId = String.valueOf(tempId);
                }
            }

        }else{//新增
            model.addObject("loanDate", DateUtils.formatDateToString(new Date(),DateUtils.YYYY_MM_DD));
            model.addObject("totalAmt","0");
            // 手机号码
            SysUsrVO sysUsrVO = sysUsrService.selectById(CurrentThreadContext.getCurrentUserId(), CurrentThreadContext.getCurrentSysCd());
            if(sysUsrVO!=null){
                model.addObject("usrMobile",sysUsrVO.getMp());
            }
            model.addObject("usrNm", CurrentThreadContext.getCurrentUserName());
            model.addObject("usrOrgCd",CurrentThreadContext.getCurrentOrgDispNm());
            model.addObject("newFlag","1");

        }


        model.setViewName("finance/loan/apply/finLoanApplyAdd");
        // 借款类型
        List<KeyValueVO> finLoanTypList = this.dictionaryApiService.getKvList(FinLoanConstant.FIN_LOAN_TYP_DIDC, FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD);
        model.addObject("finLoanTypList", JSON.toJSONString(finLoanTypList));
        // 付款方式
        List<KeyValueVO> finPayTypList = this.dictionaryApiService.getKvList(FinLoanConstant.FIN_PAY_TYP_DIDC, FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD);
        model.addObject("finPayTypList",JSON.toJSONString(finPayTypList));
        model.addObject("loanInfoId",loanInfoId);

        model.addObject("isMust",isMust);
        model.addObject("newFlag",newFlag);
        model.addObject("isAccount",isAccount);
        model.addObject("applyInfoId",applyInfoId);
        model.addObject("showSaveBtn",showSaveBtn);
        model.addObject("showSaveApplyBtn",showSaveApplyBtn);
        model.addObject("payDtlEditable",payDtlEditable);
        model.addObject("bankAccEditable",bankAccEditable);
        if(StringUtils.isEmpty(isNeedUpload)){
        	isNeedUpload="0";
        }
        model.addObject("isNeedUpload",isNeedUpload);
        return model;
    }


    /**
     * 点击保存借款信息
     * @param data 借款明细信息
     * @param loanInfoId 借款记录ID
     */
    @RequestMapping("/saveOrUpdateLoanDtl.do")
    @ResponseBody
    public Map<String, Long> saveOrUpdateLoanDtl(String data, Long loanInfoId, Long applyInfoId,String newFlag,String fileParams){
        return this.finLoanApplyService.saveOrUpdateLoanDtl(data,loanInfoId,applyInfoId,newFlag,fileParams);
    }

    @RequestMapping("initLoanDtlList")
    @ResponseBody
    public ListPageVO initLoanDtlList(Long loanInfoId){
        FinLoanDtlQC qc = new FinLoanDtlQC();
        qc.setLoanId(loanInfoId);
        List<FinLoanDtlVO> finLoanDtlVOS = this.finLoanDtlService.selectList(qc);

        return new ListPageVO(finLoanDtlVOS,finLoanDtlVOS.size());
    }
    /**
     * 付款明细列表
     * @param newFlag 是否为首次申请
     * @return
     */
    @RequestMapping("/initPayDtlList.do")
    @ResponseBody
    public ListPageVO initPayDtlList(Long applyInfoId,String newFlag){
        List<FinPayDtlGridVO> result = this.finLoanApplyService.selectPayDtlGridList(applyInfoId,newFlag);
        return new ListPageVO(result,result.size());
    }

    /**
     * action=0:暂存
     * action=1:确认并提交付款审批
     * @param action
     * @return
     */
    @RequestMapping("save.do")
    @ResponseBody
    public DataResultDTO save(@RequestParam String action, @RequestParam Long payApplyId,String payDtlList,@RequestParam(required = false,defaultValue = "0") Integer confirm){
        try {
            // 保存借款明细金额
            this.finLoanApplyService.updatePayDtlList(payDtlList);
            return this.finLoanApplyService.save(action,payApplyId, confirm);
        }catch (BaseException e){
            return new DataResultDTO("500",e.getMessage());
        }
    }
//    @RequestMapping("savePayDtlList.do")
//    @ResponseBody
//    public void savePayDtlList(String payDtlList){
//        this.finLoanApplyService.updatePayDtlList(payDtlList);
//    }

    /**
     *  保存或者暂存之前的提示信息
     * @return
     */
    @RequestMapping("saveConfirm.do")
    @ResponseBody
    public DataResultDTO saveConfirm(Long payApplyId){
        finLoanApplyService.saveConfirm(payApplyId);
        return null;
    }
    /**
	 * 跳转城配流程附加信息页面
	 */
	@RequestMapping(value = "/toLoanInfoPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAdditionalInfoList(HttpServletRequest request, HttpServletResponse response) {
		 // 手机号码finance/loan/apply/finLoanApplyAdd
		String loanInfoId = request.getParameter("loanInfoId");
		ModelAndView view = new ModelAndView("finance/loan/apply/finLoanApplyAdd");
        SysUsrVO sysUsrVO = sysUsrService.selectById(CurrentThreadContext.getCurrentUserId(), CurrentThreadContext.getCurrentSysCd());
        if(sysUsrVO!=null){
        	view.addObject("usrMobile",sysUsrVO.getMp());
        }
        view.addObject("usrNm", CurrentThreadContext.getCurrentUserName());
        view.addObject("usrOrgCd",CurrentThreadContext.getCurrentOrgCd());
        //model.setViewName("finance/loan/apply/finLoanApplyAdd");
        // 借款类型
        List<KeyValueVO> finLoanTypList = this.dictionaryApiService.getKvList(FinLoanConstant.FIN_LOAN_TYP_DIDC, FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD);
        view.addObject("finLoanTypList", JSON.toJSONString(finLoanTypList));
        // 付款方式
        List<KeyValueVO> finPayTypList = this.dictionaryApiService.getKvList(FinLoanConstant.FIN_PAY_TYP_DIDC, FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD);
        view.addObject("finPayTypList",JSON.toJSONString(finPayTypList));
        view.addObject("loanInfoId",loanInfoId);
        // 表示这是初次申请
        if(StringUtils.isBlank(loanInfoId)){
        	view.addObject("newFlag","1");
        }else{
        	view.addObject("newFlag","0");
        }
		String id = request.getParameter("id");//业务主键
		
		String isMust = request.getParameter("isMust");//0表示全部可以编辑 1表示全部不可编辑 全部是相对的
		String isAccount = request.getParameter("isAccount");//0表示帐号可以编辑 1表示帐号不可以编辑
		
		view.addObject("id", id);
		
		if(StringUtils.isNotEmpty(isMust)){
			view.addObject("isMust", isMust);
		}
		if(StringUtils.isNotEmpty(isAccount)){
			view.addObject("isAccount", isAccount);
		}
		return view;
	}

    /**
     * 发起借款流程
     * @param payApplyId
     * @return
     */
	@RequestMapping("startFlow.do")
    @ResponseBody
	public DataResultDTO startFlow(Long payApplyId){
	    return this.finLoanApplyService.startFlow(payApplyId);
    }
}
